import socket
import binascii
import pandas as pd
import numpy as np


def big_small_endian_convert(big_endian_str):
    return int(binascii.hexlify(binascii.unhexlify(big_endian_str)[::-1]), base = 16)


def load_data(filename):
    df_data = pd.read_csv(filename)

    # df_data = df_data['data'].map(lambda x: int(x[8:16][::-1], base = 16))  # Error
    # df_data = df_data['data'].map(lambda x: big_small_endian_convert(x[8:16]))  # Right  
    df_data = df_data['data'].map(lambda x: big_small_endian_convert(x[0:8]))  # Right  

    return df_data



def get_tcpdump_loss(file_sender, file_receiver):
    # sender_data = load_data('compressed_mm10_tc50M10000_sender.pcap.csv')
    # receiver_data = load_data('compressed_mm10_tc50M10000_receiver.pcap.csv')

    # sender_data = load_data('compressed_mm1_tc50M150000_sender.pcap.csv')
    # receiver_data = load_data('compressed_mm1_tc50M150000_receiver.pcap.csv')

    sender_data = load_data(file_sender)
    receiver_data = load_data(file_receiver)


    sender = set(sender_data)
    receiver = set(receiver_data)

    diff  = sender - receiver
    print(sorted(diff))
    print('sender NIC list num', len(sender_data))
    print('receiver NIC list num', len(receiver_data))
    print('sender NIC set num', len(sender))
    print('receiver NIC set num', len(receiver))
    print('packet loss num', len(diff))
    return diff



if __name__ == "__main__":
    # loss_set = get_tcpdump_loss('compressed_mm1_tc50M150000_background_sender.pcap.csv', 'compressed_mm1_tc50M150000_background_receiver.pcap.csv')
    # loss_set = get_tcpdump_loss('compressed_mm1_tc50M150000_wifi5_sender.pcap.csv', 'compressed_mm1_tc50M150000_wifi5_receiver.pcap.csv')
    # loss_set = get_tcpdump_loss('compressed_mm1_tc50M150000_wifi2_background_sender.pcap.csv', 'compressed_mm1_tc50M150000_wifi2_background_receiver.pcap.csv')
    loss_set = get_tcpdump_loss('compressed_vm_enp0s5.pcap.csv', 'compressed_laptop_en0.pcap.csv')
    loss_set = sorted(loss_set)
    # print(loss_set)
    # with open('wirelessloss.csv', 'w') as f:
    #     for seq in loss_set:
    #         f.write(str(seq) + '\n')